// 配置所有的路由
import React from 'react'
import { useHistory, Redirect, Route } from 'react-router-dom'
import { useSelector } from 'react-redux'

const whiteList = ['/login', '/404']
export default function FrontendRouter (props) {
    const history = useHistory()
    // 把路由数组导过来
    const { routerConfig } = props
    // console.log(routerConfig);
    // 把当前url的路径解构出来
    const { location: {pathname} }  = history
    // console.log(pathname);
    // 判断是否是登录状态
    const isLogin = useSelector(state => state.loginToken.isLogin)
    // console.log(isLogin);
    const targetRoute = routerConfig.find(item => {
        if(item.path === pathname) {
            return true
        } else {
            if(item.children?.length>0) {
                return item.children.find(item => item.path === pathname)
            }
        }
    })
    // console.log(targetRoute);
    // 登录状态下，目标路由若合法，则可随便去,
    //当去登录页时，则重定向到首页，若不合法，则去404页面
    if(isLogin) {
        if(targetRoute) {
            if(pathname === '/login') {
                return <Redirect to="/" />
            } else {
                return <Route path={pathname}
                    render={(props => (<targetRoute.component childrenRoutes={targetRoute.children ? targetRoute.children : []} {...props}/>))}
                       />
            }
        } else {
            return <Redirect to="/404" />
        }
    } else {
        // 非登录状态下，如果目标路由合法，则去到登录页，若不合法，则去到/404
        if(targetRoute) {
            if(whiteList.includes(pathname)) {
                return <Route component={targetRoute.component} path={pathname} />
            } else {
                return <Redirect to="/login" />
            }
        } else {
            return <Redirect to="/404" />
        }
    }
}